import java.net.*; 
import java.io.*; 
public class EchoServer2 extends Thread { 
	protected Socket clientSocket;
	public static void main(String[] args) throws IOException  { 
	    ServerSocket serverSocket = null; 
		try { 
			// creating server socket on port 10008
			serverSocket = new ServerSocket(10008); 
			System.out.println ("Connection Socket Created");
			try { 
				 while (true) {
			     	System.out.println ("Waiting for Connection");
			     	// creating a new thread to deal with the request
			     	new EchoServer2 (serverSocket.accept()); 
			     }
			}  catch (IOException e) { 
				System.err.println("Accept failed."); 
				System.exit(1); 
			} 
		} catch (IOException e) { 
			System.err.println("Could not listen on port: 10008."); 
			System.exit(1); 
		} finally {
			try {
				serverSocket.close(); 
		    } catch (IOException e){ 
		    	System.err.println("Could not close port: 10008."); 
				System.exit(1); 
		    } 
		}
	}

	private EchoServer2 (Socket clientSoc) {
		clientSocket = clientSoc;
		// runing the new thread
	 	start();
	}
	
	public void run() {
		System.out.println ("New Communication Thread Started");
		try {
			// defining output and input stream to the socket
			PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), 
                                   true); 
			BufferedReader in = new BufferedReader( 
					new InputStreamReader( clientSocket.getInputStream())); 
			String inputLine; 
			// reading message printing it and send it back to client
			while ((inputLine = in.readLine()) != null) { 
				System.out.println ("Server: " + inputLine); 
				out.println(inputLine); 
				if (inputLine.equals("Bye.")) 
					break; 
			} 
			// closing sockets
			out.close(); 
			in.close(); 
			clientSocket.close(); 
		} catch (IOException e) { 
			System.err.println("Problem with Communication Server");
			System.exit(1); 
		} 
	}
}